package com.esiran.payadmin.util;

import org.springframework.core.io.ClassPathResource;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class IOUtilEx {
    public static String readTextFile(String path) throws IOException {
        if (path == null) return null;
        InputStream is = null;
        if (path.startsWith("classpath:")){
            String classResourcePath = path.replaceAll("classpath:","");
            ClassPathResource classPathResource = new ClassPathResource(classResourcePath);
            is = classPathResource.getInputStream();
        }
        return readTextByInputStream(is);
    }
    private static String readTextByInputStream(InputStream is) throws IOException {
        if (is == null){
            return null;
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while((line=br.readLine())!=null){
            sb.append(line).append("\n");
        }
        return sb.toString();
    }

}
